//
//  AnotherFireViewController.m
//  AnotherFire
//
//  Created by pcwiz on 23/06/09.
//  Copyright leowiz 2009. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "AnotherFireViewController.h"

@implementation AnotherFireViewController
@synthesize gv;

@synthesize lblFirstName;
@synthesize lblSecondName;
@synthesize tbFirstName;
@synthesize tbSecondName;
@synthesize btnPlay;
@synthesize imgNameBG;

- (void)dealloc {
	[self,gv release];
	[self.view release];
    [super dealloc];
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
	self.view = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];
	/*	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *doc_dir = [paths objectAtIndex:0];
	
	 NSString *file_path = [doc_dir stringByAppendingString:@"save"];

	if ([[NSFileManager defaultManager] fileExistsAtPath:file_path])
	{
		NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:file_path];
		NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
		GameLogic *_gl = [unarchiver decodeObjectForKey:@"save"];
		[unarchiver finishDecoding];
		
		[unarchiver release];
		[data release];
		
		GameContorllerDelegate *gcd = [super initWithNames:self.tbFirstName.text second:self.tbSecondName.text];

		gcd.gl = _gl;
		[self startGame];
		return;
	}*/
	
	self.imgNameBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"name.png"]];
	[self.imgNameBG setFrame:CGRectMake(0, 0, 320, 480)];
	[self.view addSubview: self.imgNameBG];
	
	self.tbFirstName = [[UITextField alloc] initWithFrame:CGRectMake(150, 80, 120, 30)];
	self.tbFirstName.text = @"Choose";
	self.tbFirstName.delegate = self;
	[self.view addSubview: self.tbFirstName];
	
	self.tbSecondName = [[UITextField alloc] initWithFrame:CGRectMake(150, 195, 120, 30)];
	self.tbSecondName.text = @"name";
	self.tbSecondName.delegate = self;
	[self.view addSubview: self.tbSecondName];
	
	
	self.btnPlay = [UIButton buttonWithType:UIButtonTypeCustom];
	[self.btnPlay setTitle:@"" forState:UIControlStateNormal];
	[self.btnPlay setFrame:CGRectMake(125, 315, 98, 32)];
	[self.btnPlay setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
	[self.btnPlay addTarget:self action:@selector(settingsChanged) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview: self.btnPlay];
	
}

- (BOOL) textFieldShouldReturn:(UITextField *) sender
{
	[sender resignFirstResponder];
	return YES;
}

- (void) pre_promo
{
	self.view = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)];

	NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
	NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
	
	AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error:nil];
	[fileURL release];
	[player prepareToPlay];
	[player play];

	self.btnPlay = [UIButton buttonWithType:UIButtonTypeCustom];
	[self.btnPlay setFrame:CGRectMake(0, 0, 320, 480)];
	[self.btnPlay addTarget:self action:@selector(post_intro) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:self.btnPlay];
	
	self.imgNameBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"intro.png"]];
	[self.imgNameBG setFrame:CGRectMake(0, 0, 320, 480)];
	[self.view addSubview:self.imgNameBG];
	NSTimer *intro_timer = [NSTimer scheduledTimerWithTimeInterval: 2.5 target:self selector:@selector(timer_done) userInfo:nil repeats:NO];
}

- (void) timer_done: (NSTimer *)timer
{
	[self post_intro];
}


- (void) touchOccured: (CGPoint) _where;
{
	printf("A touch occured at: %f, %f.\n", _where.x, _where.y);
	
	int where;
	int columns[8] = {55, 91, 128, 165, 201, 237, 276, 500};
	for (int i = 0; i < 8 ; ++i)
	{
		if (_where.x < columns[i])
		{
			where = i;
			break;
		}
	}
	
	int height = [self.gl moveTo:where];
	
	if (-1 != height)
	{
		[self.gv animateMove:where col:height];
	}
	else
	{
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Bad move!" message:@"You can't put a coin in a full row." delegate:nil cancelButtonTitle:@"Understood!" otherButtonTitles:nil];
		[av show];
		[av release];
	}
	
	NSString *str = [gl whoWon];
	if (@"" != str)
	{
		NSString *msg = [str  stringByAppendingString: @" won. Laugh at the other player."];
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"We have a winner!" message:msg delegate:self cancelButtonTitle:@"New Game" otherButtonTitles:nil];
		[av setDelegate:self];
		[av show];
		[av release];
	}
	
	if ([gl isBoardFull])
	{
		NSString *msg = @"It's a tie. You both lost.";
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Tie" message:msg delegate:self cancelButtonTitle:@"New Game" otherButtonTitles:nil];
		[av setDelegate:self];
		[av show];
		[av release];
	}
	
}


-(void) settingsChanged
{
	[super initWithNames:self.tbFirstName.text second:self.tbSecondName.text];

	[self.btnPlay removeFromSuperview];
	[self.lblFirstName removeFromSuperview];
	[self.lblSecondName removeFromSuperview];
	[self.tbFirstName removeFromSuperview];
	[self.tbSecondName removeFromSuperview];
	 	
	[self startGame];
}

//Actually start the game with that number of players:
-(void) startGame
{
	printf("Starting the game.\n");
	self.gv = [[GameView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[self.gv setNeedsDisplay];
	[self.gv newParent: self];
	[self.view addSubview: self.gv];

}

-(void) saveGame
{/*
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *doc_dir = [paths objectAtIndex:0];
	NSString *file_path = [doc_dir stringByAppendingString:@"save"];
	
	@try
	{
	NSMutableData *data = [[NSMutableData alloc] init];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	[archiver encodeObject:self.gl forKey:@"save"];
	[archiver finishEncoding];
	[data writeToFile:file_path atomically:YES];
	[archiver release];
	[data release];	
	}
	@catch (NSException *e) {
		[e retain];
		
	}
*/}

-(void) alertView: (UIAlertView *)_alert_view clickedButtonAtIndex:(NSInteger)_button
{
		printf("A new game is beggining.");
	
	[self.gl startGame];
	[self.gv removeFromSuperview];
	[self.gv dealloc];
	[self startGame];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

@end
